package com.todod.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.mapper.PublicFileAuthorityMapper;
import com.todod.model.PublicCatalog;
import com.todod.model.PublicFile;
import com.todod.model.PublicFileAuthority;
import com.todod.model.UserRole;

/**
 * @param
 * @author dyl
 * @date 2021-03-16
 */
@Service
@Transactional
public class PublicFileAuthorityService {
	@Autowired
	private PublicFileAuthorityMapper publicFileAuthorityMapper;
	@Autowired
	public PublicCatalogService publicCatalogService;
	@Autowired
	private PublicFileService publicFileService;
	@Autowired
	private IUserRoleService iUserRoleService;

	/*
	 * @title saveData
	 * 
	 * @description 保存文件夹及文件权限
	 * 
	 * @param _userId
	 * 
	 * @param fileId
	 * 
	 * @param List<String> userIds
	 * 
	 * @param type
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public void saveData(Long _userId, Long fileId, List<String> userIds, String type) {
		this.deleteByFileId(fileId);
		List<PublicCatalog> list = publicCatalogService.getSelfAndChildren(fileId);
		this.saveAllAuthority(list, _userId, fileId, userIds, type);
	}

	/**
	 * @title saveFileWDAuthorit
	 * @description 角色文档权限分配
	 * @param _userId
	 * @param roleId
	 * @param List<String> roleFiles
	 * @return
	 */
	public void saveFileWDAuthorit(Long _userId, Long roleId, List<String> roleFiles) {
		List<UserRole> userRoleList = iUserRoleService.getByRoleId(roleId);
		if (userRoleList != null) {
			// 删除现有数据
			userRoleList.forEach(x -> {
				Long userId = x.getUserId();
				List<PublicFileAuthority> listAuthority = this.getFileAuthorityByUserId(userId);
				if (listAuthority != null) {
					listAuthority.forEach(y -> {
						this.deleteById(y.getId());
					});
				}
			});

			// 新增当前数据
			if (userRoleList != null && userRoleList.size() > 0) {
				List<String> userIds = userRoleList.stream().map(x -> x.getUserId().toString())
						.collect(Collectors.toList());
				if (roleFiles != null) {
					roleFiles.forEach(x -> {
						Long fileId = Long.valueOf(x);
						this.saveAuthority(_userId, fileId, userIds, "M");
					});
				}
			}

		}
	}

	/**
	 * @title saveFileWDAuthorit
	 * @description 根据文件id和用户获取权限分配
	 * @param fileId
	 * @param userId
	 * @return List<PublicFileAuthority>
	 */
	public List<PublicFileAuthority> getAuthorityByFileIdAndUserId(Long fileId, Long userId) {
		QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gfa_file_id", fileId);
		queryWrapper.eq("gfa_user_id", userId);
		return publicFileAuthorityMapper.selectList(queryWrapper);
	}

	/*
	 * 
	 * @title deleteById
	 * 
	 * @description 根据id删除权限
	 * 
	 * @param id
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public void deleteById(Long id) {
		publicFileAuthorityMapper.deleteById(id);
	}

	/*
	 * @title saveAllAuthority
	 * 
	 * @description 保存文件夹下所有文件夹及文件权限
	 * 
	 * @param List<PublicCatalog>
	 * 
	 * @param _userId
	 * 
	 * @param fileId
	 * 
	 * @param List<String> userIds
	 * 
	 * @param type
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public void saveAllAuthority(List<PublicCatalog> list, Long _userId, Long fileId, List<String> userIds,
			String type) {
		list.forEach(x -> {
			List<PublicFile> listFile = x.getListFile();
			if (listFile != null) {
				listFile.forEach(y -> {
					saveAuthority(_userId, Long.valueOf(y.getBatchCode()), userIds, type);
				});
			}
			if (x.getChildren2() != null && x.getChildren2().size() > 0) {
				saveAllAuthority(x.getChildren2(), _userId, fileId, userIds, type);
			} else {
				if (listFile == null || listFile.size() <= 0) {
					saveAuthority(_userId, x.getId(), userIds, type);
				}

			}
		});
	}

	/*
	 * @title saveAuthority
	 * 
	 * @description 保存文件夹下所有文件夹及文件权限
	 * 
	 * @param _userId
	 * 
	 * @param fileId
	 * 
	 * @param List<String> userIds
	 * 
	 * @param type
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public void saveAuthority(Long _userId, Long fileId, List<String> userIds, String type) {
		for (int i = 0; i < userIds.size(); i++) {
			Boolean flag = publicCatalogService.createorIsUserMOU(Long.valueOf(userIds.get(i)), fileId);
			PublicFileAuthority fileAuthority = getAuthorityByFileId(fileId, userIds.get(i));
			if (fileAuthority == null && flag) {
				PublicFileAuthority fileAuthorit = new PublicFileAuthority();
				fileAuthorit.setId(SnowflakeIdGenerator.getId());
				fileAuthorit.setUserId(Long.valueOf(userIds.get(i)));
				fileAuthorit.setFileId(fileId);
				fileAuthorit.setCreatetimeTi(LocalDateTime.now());
				fileAuthorit.setCreateuserId(_userId);
				publicFileAuthorityMapper.insert(fileAuthorit);
			} else {
				PublicFileAuthority fileAuthorit = new PublicFileAuthority();
				fileAuthorit.setId(SnowflakeIdGenerator.getId());
				fileAuthorit.setUserId(Long.valueOf(userIds.get(i)));
				fileAuthorit.setFileId(fileId);
				fileAuthorit.setCreatetimeTi(LocalDateTime.now());
				fileAuthorit.setCreateuserId(_userId);
				publicFileAuthorityMapper.insert(fileAuthorit);
			}
		}
	}

	public List<PublicFileAuthority> getFileAuthorityByFileIdId(Long fileId) {
		QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gfa_file_id", fileId);

		List<PublicFileAuthority> list = publicFileAuthorityMapper.selectList(queryWrapper);
		return list;
	}

	public PublicFileAuthority getAuthorityByFileId(String batchCode) {
		QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gfa_file_id", batchCode);

		PublicFileAuthority publicFileAuthority = publicFileAuthorityMapper.selectOne(queryWrapper);
		return publicFileAuthority;
	}

	public PublicFileAuthority getAuthorityByFileId(Long fileId, String userId) {
		QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gfa_file_id", fileId);
		queryWrapper.eq("gfa_user_id", userId);

		PublicFileAuthority publicFileAuthority = publicFileAuthorityMapper.selectOne(queryWrapper);
		return publicFileAuthority;
	}

	/*
	 * 
	 * @title deleteByFileId
	 * 
	 * @description 根据fileId删除当前文件权限
	 * 
	 * @param fileId
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public void deleteByFileId(Long fileId) {
		// 当前文件夹下面的文件夹和文件存在 删除当前文件夹下面的文件夹和文件
		if (publicCatalogService.getListCatalogByParentId(fileId).size() > 0
				|| publicFileService.getListFileByParentId(fileId).size() > 0) {
			// 获取所有子节点
			List<PublicCatalog> list = publicCatalogService.getSelfAndChildren(fileId);
			deleteChildren(list);
		} else {
			delete(fileId);
		}
	}

	/*
	 * 
	 * @title delete
	 * 
	 * @description 根据fileId删除权限，除创建者
	 * 
	 * @param fileId
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public void delete(Long fileId) {
		QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gfa_file_id", fileId);
		List<PublicFileAuthority> authList = publicFileAuthorityMapper.selectList(queryWrapper);
		for (PublicFileAuthority fileAuthority : authList) {
			// 如果授权用户不是创建者
			if (publicCatalogService.createorIsUserMOU(fileAuthority.getUserId(), fileId)) {
				publicFileAuthorityMapper.deleteById(fileAuthority.getId());
			}

		}
	}

	/*
	 * @title deleteChildren
	 * 
	 * @description 删除文件夹下所有文件夹及文件权限
	 * 
	 * @param List<PublicCatalog>
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public void deleteChildren(List<PublicCatalog> list) {
		list.forEach(x -> {

			List<PublicFile> listFile = x.getListFile();
			if (listFile != null) {
				listFile.forEach(y -> {
					delete(Long.valueOf(y.getBatchCode()));
				});
			}
			if (x.getChildren2() != null && x.getChildren2().size() > 0) {
				deleteChildren(x.getChildren2());
			} else {
				if (x.getId() != null) {
					delete(x.getId());
				}
			}
		});
	}

	public List<PublicFileAuthority> getFileAuthorityByUserId(Long userId) {
		QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gfa_user_id", userId);

		List<PublicFileAuthority> list = publicFileAuthorityMapper.selectList(queryWrapper);
		return list;
	}

	/*
	 * 
	 * @title getUserIdInMax
	 * 
	 * @description 根据用户list获取权限最多用户id
	 * 
	 * @auth wgb
	 * 
	 * @date 2021-06-29
	 * 
	 * @return
	 */
	public Long getUserIdInMax(List<Long> hashUser) {
		return publicFileAuthorityMapper.getUserIdInMax(hashUser);
	}

	/**
	 * @title: deleteAuthByFileIdAndType
	 * @Description: 根据文件id和类型删除权限 @param： fileId @param： type (1:文件夹；2：文件)
	 * @author: wgb
	 * @date: 2022年4月10日
	 * @return:
	 */
	public void deleteAuthByFileIdAndType(Long fileId, String type) {
		if (type.equalsIgnoreCase("1")) {

		} else {
			deleteAuthByFileId(fileId);
		}
	}

	/**
	 * @title: deleteAuthByFileId
	 * @Description: 根据文件id删除权限 @param： fileId
	 * @author: wgb
	 * @date: 2022年4月10日
	 * @return:
	 */
	public void deleteAuthByFileId(Long fileId) {
		QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gfa_file_id", fileId);
		List<PublicFileAuthority> list = publicFileAuthorityMapper.selectList(queryWrapper);
		list.forEach(x -> {
			this.deleteById(x.getId());
			;
		});
	}

}
